package com.algernoon.rpc.springrpc.rmi.natives.impl;

import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.algernoon.rpc.springrpc.entity.User;
import com.algernoon.rpc.springrpc.rmi.natives.IUserService;

@Service
public class UserServiceImpl extends UnicastRemoteObject implements IUserService {

	private static final long serialVersionUID = -3594332402051129324L;

	Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	public Map<Integer, User> map = new HashMap<Integer, User>() {

		private static final long serialVersionUID = 3090616293630317141L;

		{
			put(1, new User(1, "zhangsan", "123456"));
			put(2, new User(2, "lisi", "123456"));
			put(3, new User(3, "wangwu", "123456"));
			put(4, new User(4, "zhaoliu", "123456"));
		}
	};
	
	protected UserServiceImpl() throws RemoteException {
		super();
	}
	
	@PostConstruct
	public void init() {
		logger.info("constructor UserServiceImpl initialing..." + this);
		try {
			
			 //本地主机上的远程对象注册表Registry的实例，并指定端口为8888，这一步必不可少（Java默认端口是1099），必不可缺的一步，缺少注册表创建，则无法绑定对象到远程注册表上 
			LocateRegistry.createRegistry(8888);
			
	        //把远程对象注册到RMI注册服务器上，并命名为UserService
			//绑定的URL标准格式为：rmi://host:port/name(其中协议名可以省略，下面两种写法都是正确的）
			Naming.bind("rmi://localhost:8888/UserService", this);
//			Naming.bind("//localhost:8888/UserService", this);
			
			logger.info("远程服务UserService绑定成功。");
			
		} catch (RemoteException e) {
			logger.error("创建远程对象发生异常！");
			e.printStackTrace();
		} catch (MalformedURLException e) {
			logger.error("发生重复绑定对象异常！");
			e.printStackTrace();
		} catch (AlreadyBoundException e) {
			logger.error("发生URL畸形异常！");
			e.printStackTrace();
		}
	}
	
	@Override
	public User findUserById(Integer id) throws RemoteException {
		return map.get(id) ;
	}

}
